package com.reactim.user.repository;

import com.reactim.user.entity.UserFriend;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import java.util.List;
import java.util.Optional;

/**
 * 用户好友关系数据访问接口
 */
@Repository
public interface UserFriendRepository extends JpaRepository<UserFriend, Long> {
    
    /**
     * 查找用户的所有好友
     */
    @Query("SELECT uf FROM UserFriend uf WHERE uf.userId = :userId AND uf.status = :status")
    List<UserFriend> findFriendsByUserId(@Param("userId") Long userId, @Param("status") UserFriend.FriendStatus status);
    
    /**
     * 查找特定好友关系
     */
    Optional<UserFriend> findByUserIdAndFriendId(Long userId, Long friendId);
    
    /**
     * 检查是否为好友关系
     */
    @Query("SELECT COUNT(uf) > 0 FROM UserFriend uf WHERE uf.userId = :userId AND uf.friendId = :friendId AND uf.status = :status")
    boolean isFriend(@Param("userId") Long userId, @Param("friendId") Long friendId, @Param("status") UserFriend.FriendStatus status);
    
    /**
     * 检查是否被拉黑
     */
    @Query("SELECT COUNT(uf) > 0 FROM UserFriend uf WHERE uf.userId = :userId AND uf.friendId = :friendId AND uf.status = :status")
    boolean isBlocked(@Param("userId") Long userId, @Param("friendId") Long friendId, @Param("status") UserFriend.FriendStatus status);
    
    /**
     * 获取用户的好友数量
     */
    @Query("SELECT COUNT(uf) FROM UserFriend uf WHERE uf.userId = :userId AND uf.status = :status")
    long countFriendsByUserId(@Param("userId") Long userId, @Param("status") UserFriend.FriendStatus status);
    
    /**
     * 删除好友关系（双向）
     */
    void deleteByUserIdAndFriendId(Long userId, Long friendId);
    
    /**
     * 检查是否存在好友关系
     */
    boolean existsByUserIdAndFriendId(Long userId, Long friendId);
    
    /**
     * 根据分组查找好友
     */
    List<UserFriend> findByUserIdAndGroupId(Long userId, Long groupId);
    
    /**
     * 批量查找好友
     */
    List<UserFriend> findByUserIdAndFriendIdIn(Long userId, List<Long> friendIds);
    
    /**
     * 统计分组中的好友数量
     */
    long countByUserIdAndGroupId(Long userId, Long groupId);
    
    /**
     * 统计未分组的好友数量
     */
    long countByUserIdAndGroupIdIsNull(Long userId);
    
    /**
     * 检查是否存在共同好友（朋友的朋友）
     */
    @Query("SELECT COUNT(*) > 0 FROM UserFriend uf1, UserFriend uf2, UserFriend uf3, UserFriend uf4 " +
           "WHERE uf1.userId = :fromUserId AND uf1.status = 'NORMAL' " +
           "AND uf2.userId = uf1.friendId AND uf2.friendId = :toUserId AND uf2.status = 'NORMAL' " +
           "AND uf3.userId = :toUserId AND uf3.friendId = uf1.friendId AND uf3.status = 'NORMAL' " +
           "AND uf4.userId = uf1.friendId AND uf4.friendId = :fromUserId AND uf4.status = 'NORMAL'")
    boolean existsMutualFriends(@Param("fromUserId") Long fromUserId, @Param("toUserId") Long toUserId);
}